import { fetchProduct } from "@/api";
import {ImmerReducer,Effect} from "umi"
export interface stateType{//定义state接口
    productList:object[] | [],
    err:string | null
}
export interface ProductModelType{//定义modal接口
    namespace: string;
    state:stateType;
    reducers:{
        setProductList:ImmerReducer<stateType>//ImmerReducer用来方便的更新状态
    };
    effects:{
        getProductList:Effect
    }

}
 const ProductModel:ProductModelType ={
    namespace:"product",//命名空间，
    state:{
        productList:[],
        err:null
    },
    reducers:{
        setProductList(state,action){
            state.productList = action.payload.data;
            // console.log(action.payload.err);       
            state.err = action.payload.err;
        }
    },
    effects:{//副作用，相当于vuex中国的actions
        *getProductList({payload},{call,put}):any{
            // 获取数据，更新reducer
            yield new Promise((resolve,reject)=>{
                setTimeout(() => {
                    resolve(123)
                }, 2000);
            })
            try{
                const res:any = yield call(fetchProduct)
                yield put({type:"setProductList",payload:{data:res.data,err:null}})
            }catch(e:any){
                console.log(e);
                yield put({type:"setProductList",payload:{data:[],err:e.toString()}})
            }
        }
    }
}
export default ProductModel